package com.own.component.util.excel.util.append;

import com.own.component.common.exception.BusinessException;
import com.own.component.util.excel.method.WorkbookMethod;
import com.own.component.util.excel.util.write.method.ExcelWriteUtil;
import com.own.component.util.excel.util.write.record.ExcelRecord;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.util.UUID;

/**
 * ExcelAppend
 *
 * @author chenxueli
 * @date 2022-10-09 15:02:00
 */
@Slf4j
public class ExcelAppend {

    /**
     * 追加excel中的内容
     *
     * @param file        excel文件
     * @param excelRecord excel记录
     */
    public File append(File file, ExcelRecord excelRecord) {
        // 读取原文件信息
        var workbook = WorkbookMethod.get(file);
        if (!(workbook instanceof XSSFWorkbook)) {
            throw new BusinessException("excel模板的版本不是xlsx,请将模板转换为xlsx后重试");
        }
        // 名称信息需要随机
        excelRecord.setFileName(UUID.randomUUID().toString());
        // 创建的是临时文件
        return new ExcelWriteUtil().write(excelRecord, null, () -> (XSSFWorkbook) workbook, null, null);
    }

}
